<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %> 
<!DOCTYPE html>
<html>
	<head>
		<!-- jsp文件头和头部 -->
		<%@ include file="../common/top.jsp"%>
		
		<script type="text/javascript" src="<%=basePath%>/resources/zTree/jquery.ztree.all.min.js"></script>
	
		<link rel="stylesheet" type="text/css" href="<%=basePath%>/resources/zTree/zTreeStyle/zTreeStyle.css">
		
		<script type="text/javascript">
		
			var authTree, groupTree;
			
			$(function(){
				$(window).resize(function(){
					var fullScreen = getFullScreen("grid");
					$("#grid").datagrid('resize',{height:fullScreen});
				});
				
				$(window).trigger('resize');
				
				initGroupTree();
			});
			
			function initGroupTree(){
				if(!groupTree){
					var setting = {
						data: {
							key: {
								name: "groupName"
							},
							simpleData: {
								enable: true,
								idKey: "groupId",
								pIdKey: "groupPid",
								rootPId: 1
							}
						},
						view: {
							selectedMulti: false
						},
						callback: {
							onClick: doSearch
						}
					};
					
					$.ajax({
						url:'<%=basePath%>/group/getGroups',
						type:'post',
						dataType:'json',
						success:function(result){
							if (result.errorMsg){
								$.messager.alert('Error',result.errorMsg);
							} else {
								groupTree = $.fn.zTree.init($("#groupTree"), setting, result);
								
								groupTree.expandAll(true);
								
								var nodes = groupTree.getNodes();
								if (nodes.length>0) {
									groupTree.selectNode(nodes[0]);
									doSearch(null, groupTree, nodes[0]);
								}
							}
						}
					});
				}
			}
			
			
			function doSearch(event, treeId, treeNode){
				var opts = $("#grid").datagrid("options");
				if(!opts.url){
					var url = '<%=basePath%>/role/getRoles';
				    opts.url = url;
				}
			    
				var param = {};
				var groupParam;
				if(treeNode){ //点击权限树树,忽略搜索条件
					groupParam = {groupId:treeNode.groupId};
					$.extend(param, groupParam);
				}else{ //点击查询按钮
					groupParam = {groupId:opts.queryParams.groupId};
					$.extend(param, groupParam, $("#searchForm").serializeObject());
				}
				
				$("#grid").datagrid('load', param);
			}
		
			<shiro:hasPermission name="AddRole">
			function showAddRole(){
				$('#addDlg').dialog('open');
				$('#addForm').form('reset');
				
				var nodes = groupTree.getSelectedNodes();
				$('#addGroupId').val(nodes[0].groupId);
			}
			</shiro:hasPermission>
			
			<shiro:hasPermission name="EditRole">
			function showEditRole(){
				var row = $('#grid').datagrid('getSelected');
				if (row){
					$('#editDlg').dialog('open');
					$('#editForm').form('load',row);
				}else{
					$.messager.alert("提示","请选择需要编辑的角色");
				}
			}
			</shiro:hasPermission>
			
			<shiro:hasPermission name="AllotAuth">
			function showRoleAuth(){
				var row = $('#grid').datagrid('getSelected');
				if (row){
					$('#authDlg').dialog('open');
					
					$('#auth_roleId').val(row.roleId);
					
					getAuthTree(row.roleId);
				}else{
					$.messager.alert("提示","请选择需要分配权限的角色");
				}
			}
			</shiro:hasPermission>
			
			<shiro:hasPermission name="AddRole">
			function doAddRole(){
				$('#addForm').form('submit',{
					onSubmit: function(){
						return $(this).form('validate');
					},
					success: function(result){
						var result = eval('('+result+')');
						if (result.errorMsg){
							$.messager.alert('Error',result.errorMsg);
						} else {
							$('#addDlg').dialog('close');
							$('#grid').datagrid('reload');
						}
					}
				});
			}
			</shiro:hasPermission>
			
			<shiro:hasPermission name="EditRole">
			function doEditRole(){
				$('#editForm').form('submit',{
					onSubmit: function(){
						return $(this).form('validate');
					},
					success: function(result){
						var result = eval('('+result+')');
						if (result.errorMsg){
							$.messager.alert('Error',result.errorMsg);
						} else {
							$('#editDlg').dialog('close');
							$('#grid').datagrid('reload');
						}
					}
				});
			}
			</shiro:hasPermission>
			
			<shiro:hasPermission name="DelRole">
			function doDelRole(){
				var row = $('#grid').datagrid('getSelected');
				if (row){
					$.messager.confirm('确认','确定删除该角色?',function(r){
						if (r){
							$.ajax({
								url:'<%=basePath%>/role/delRole',
								data:{roleId:row.roleId},
								type:'post',
								dataType:'json',
								success:function(result){
									if (result.errorMsg){
										$.messager.alert('Error',result.errorMsg);
									} else {
										$('#grid').datagrid('reload');
									}
								}
							});
						}
					});
				}else{
					$.messager.alert("提示","请选择需要删除的角色");
				}
			}
			</shiro:hasPermission>
			
			<shiro:hasPermission name="AllotAuth">
			function doUpdateRoleAuths(){
				var authIds = new Array();
				
				var allowIds = new Array();
				$('.allow_chk').find('input:checkbox:checked').each(function(i){
					allowIds.push($(this).attr('authid'));
				});
				
				var nodes = authTree.getCheckedNodes(true);
				
				for(var i=0,len=nodes.length; i<len; i++){
					authIds.push({
						authId : nodes[i].authId,
						allowAuth : allowIds.indexOf(nodes[i].authId) >= 0 ? true : false
					});
				}
				
				var roleId = $('#auth_roleId').val();
				
				$.ajax({
					url:'<%=basePath%>/role/updateRoleAuths',
					data:JSON.stringify({roleId:roleId, authIds:authIds}),
					contentType:"application/json;charset=UTF-8",
					type:'post',
					dataType:'json',
					success:function(result){
						if (result.errorMsg){
							$.messager.alert('Error',result.errorMsg);
						} else {
							$('#authDlg').dialog('close');
						}
					}
				});
			}
			
			function getAuthTree(roleId){
				var setting = {
					data: {
						key: {
							name: "authName"
						},
						simpleData: {
							enable: true,
							idKey: "authId",
							pIdKey: "authParent",
							rootPId: 1
						}
					},
					check: {
						enable: true,
						chkStyle: "checkbox",
						chkboxType: { "Y": "p", "N": "s" }
					},
					callback: {
						onCheck: authTreeOnCheck,
						onNodeCreated: authTreeOnNodeCreated
					}
				};
				
				$.ajax({
					url:'<%=basePath%>/role/getRoleAuths',
					data:{roleId:roleId},
					type:'post',
					dataType:'json',
					success:function(result){
						if (result.errorMsg){
							$.messager.alert('Error',result.errorMsg);
						} else {
							authTree = $.fn.zTree.init($("#authTree"), setting, handleAuthTreeData(result));
						}
					}
				});
			}
			
			function handleAuthTreeData(data){
				
				var auths = data.allAuths;
				var roleAuthIds = data.roleAuthIds;
				var roleAllowAuthIds = data.roleAllowAuthIds;
				
				for(var i=0,len=auths.length; i<len; i++){
					if(auths[i].authType == 0){
						auths[i].isParent = true;
						auths[i].open = true;
						auths[i].nocheck = true;
					}else if(auths[i].authType == 1 || auths[i].authType == 2){
						auths[i].isParent = true;
						auths[i].open = true;
						auths[i].checked = (roleAuthIds.indexOf(auths[i].authId) >= 0);
						auths[i].allow = (roleAllowAuthIds.indexOf(auths[i].authId) >= 0);
					}else{
						auths[i].isParent = false;
						auths[i].checked = (roleAuthIds.indexOf(auths[i].authId) >= 0);
						auths[i].allow = (roleAllowAuthIds.indexOf(auths[i].authId) >= 0);
					}
				}
				return auths;
			}
			
			//树节点创建事件
			function authTreeOnNodeCreated(event, treeId, treeNode) {
				var aObj = $("#" + treeNode.tId + "_a");
				
				if (treeNode.checked && $("#allowSpan_"+treeNode.tId).length==0){
					var checkStr = "<span id='allowSpan_" + treeNode.tId + "' class='allow_chk'>&nbsp;&nbsp;(<input type='checkbox' style='width:13px;height:13px;vertical-align:middle;' authid='" + treeNode.authId + "' id='allowCheck_" + treeNode.tId + "' onclick='allowOnCheck(this)'>可授权</input>)</span>";
						
					aObj.append(checkStr);
					
					if(treeNode.allow){
						$('#allowCheck_' + treeNode.tId).prop("checked","checked");
					}
				}
			};
			
			//树节点勾选事件,勾选树节点后显示是否可授权的checkbox,取消树节点勾选则去掉该checkbox的显示
			function authTreeOnCheck(event, treeId, treeNode) {
				var aObj = $("#" + treeNode.tId + "_a");
				
				if (treeNode.checked && $("#allowSpan_"+treeNode.tId).length==0){
					var checkStr = "<span id='allowSpan_" + treeNode.tId + "' class='allow_chk'>&nbsp;&nbsp;(<input type='checkbox' style='width:13px;height:13px;vertical-align:middle;' authid='" + treeNode.authId + "' id='allowCheck_" + treeNode.tId + "' onclick='allowOnCheck(this)'>可授权</input>)</span>";
						
					aObj.append(checkStr);
				}else if(!treeNode.checked){
					$("#allowSpan_"+treeNode.tId).remove();
					
					$('#'+treeNode.tId+'_ul').find('.allow_chk').remove();
				}
				
				//递归触发父节点的勾选事件
				if(treeNode.authType != 1){
					authTreeOnCheck(event, treeId, treeNode.getParentNode());
				}
			};
			
			//可授权checkbox点击事件
			function allowOnCheck(event){
				if($(event).is(':checked')){ //勾选,父节点自动勾选
					$(event).parents("li").children('a').children('.allow_chk').children('input').prop("checked","checked");
				}else{ //取消勾选,子节点自动取消勾选
					$(event).parent().parent().parent().find('.allow_chk').children('input').removeAttr("checked");
				}
			}
			
			</shiro:hasPermission>
			
			function formatterRoleType(value,row,index){
				if(value == 1){
					return '普通角色';
				}else if(value == 2){
					return '<font color="#0000FF">默认角色</font>';
				}else{
					return '未知';
				}
			}
		</script>
	</head>
	
	<body >
		<div class="easyui-layout" data-options="fit:true">
			<div data-options="region:'west', border:false" style="width:180px;padding:10px 0px 10px 10px" >
				<div class="easyui-panel" style="width:100%;height:100%;">
					<ul id="groupTree" class="ztree"></ul>
				</div>
			</div>

			<div data-options="region:'center', border:false" style="padding:10px" >
		
				<div id="searchDiv" class="easyui-panel" style="width:100%;padding:10px;margin-bottom: 10px;">
					<form id="searchForm">
						<label for="roleName">角色名:</label>
						<input class="easyui-validatebox" type="text" id="roleName" name="roleName" />
						
						<a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-search'" onclick="doSearch()">搜索</a>
					</form>
				</div>
				
				<div id="tb">
					<shiro:hasPermission name="AddRole">
						<a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="showAddRole()">新增角色</a>
					</shiro:hasPermission>
					<shiro:hasPermission name="EditRole">
						<a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="showEditRole()">编辑角色</a>
					</shiro:hasPermission>
					<shiro:hasPermission name="DelRole">
						<a href="#" class="easyui-linkbutton" iconCls="icon-cut" plain="true" onclick="doDelRole()">删除角色</a>
					</shiro:hasPermission>
					<shiro:hasPermission name="AllotAuth">
						<a href="#" class="easyui-linkbutton" iconCls="icon-filter" plain="true" onclick="showRoleAuth()">分配角色权限</a>
					</shiro:hasPermission>
				</div>
				
				<table id="grid" class="easyui-datagrid" style="width:100%;"
					data-options="pagination:true,fitColumns:true,singleSelect:true,toolbar:'#tb'">
					<thead>
						<tr>
							<th data-options="field:'roleId',width:100">角色id</th>
							<th data-options="field:'roleName',width:100">角色名</th>
							<th data-options="field:'roleType',width:100,formatter:formatterRoleType">角色类型</th>
							<th data-options="field:'roleDesc',width:100">描述</th>
						</tr>
					</thead>
				</table>
				
				<%-- 新增 --%>
				<shiro:hasPermission name="AddRole">
					<div id="addDlg" class="easyui-dialog" style="width:400px;height:330px;padding:10px 20px"
						closed="true" buttons="#addDlgBtns" title="新增角色" modal="true" resizable="true">
						<div class="ftitle">角色信息</div>
						<form id="addForm" method="post" data-options="url:'<%=basePath%>/role/addRole'">
							<div class="fitem">
								<label>角色名:</label>
								<input name="roleName" class="easyui-validatebox" required="true">
							</div>
							<div class="fitem">
								<label>类型:</label>
								<select name="roleType" class="easyui-combobox">
								    <option value="1" selected="selected">普通角色</option>
								    <option value="2">默认角色</option>
								</select>
							</div>
							<div class="fitem">
								<label>描述:</label>
								<textarea name="roleDesc" class="easyui-validatebox" style="width: 250px; height: 100px;"></textarea>
							</div>
							<input id="addGroupId" name="groupId" type="hidden">
						</form>
					</div>
					<div id="addDlgBtns">
						<a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="doAddRole()">保存</a>
						<a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#addDlg').dialog('close')">取消</a>
					</div>
				</shiro:hasPermission>
				
				<%-- 编辑 --%>
				<shiro:hasPermission name="EditRole">
					<div id="editDlg" class="easyui-dialog" style="width:400px;height:330px;padding:10px 20px"
						closed="true" buttons="#editDlgBtns" title="编辑角色" modal="true" resizable="true">
						<div class="ftitle">角色信息</div>
						<form id="editForm" method="post" data-options="url:'<%=basePath%>/role/editRole'">
							<div class="fitem">
								<label>角色Id:</label>
								<input name="roleId" class="easyui-validatebox" readonly="readonly">
							</div>
							<div class="fitem">
								<label>角色名:</label>
								<input name="roleName" class="easyui-validatebox" required="true">
							</div>
							<div class="fitem">
								<label>类型:</label>
								<select name="roleType" class="easyui-combobox" >
								    <option value="1">普通角色</option>
								    <option value="2">默认角色</option>
								</select>
							</div>
							<div class="fitem">
								<label>描述:</label>
								<textarea name="roleDesc" class="easyui-validatebox" style="width: 250px; height: 100px;"></textarea>
							</div>
							<input name="groupId" type="hidden">
						</form>
					</div>
					<div id="editDlgBtns">
						<a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="doEditRole()">保存</a>
						<a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#editDlg').dialog('close')">取消</a>
					</div>
				</shiro:hasPermission>
				
				<%-- 分配角色权限 --%>
				<shiro:hasPermission name="AllotAuth">
					<div id="authDlg" class="easyui-dialog" style="width:400px;height:300px;padding:10px 20px"
						closed="true" buttons="#authDlgBtns" title="分配权限" modal="true" resizable="true">
						<input id="auth_roleId" name="roleId" type="hidden" >
						<ul id="authTree" class="ztree"></ul>
					</div>
					<div id="authDlgBtns">
						<a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="doUpdateRoleAuths()">保存</a>
						<a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#authDlg').dialog('close')">取消</a>
					</div>
				</shiro:hasPermission>
			</div>
		</div>
	</body>
</html>